<template>
	<div class="table-box">
		<ProTable
			ref="proTable"
			title="客户列表"
			:columns="columns"
			:requestApi="getTableList"
			:initParam="initParam"
			:dataCallback="dataCallback"
		>
			<!-- 表格 header 按钮 -->
			<template #tableHeader="scope">
				<!-- <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')">新增客户</el-button> -->
				<!-- <el-button type="primary" :icon="Upload" plain @click="batchAdd" v-auth="'batchAdd'">批量添加用户</el-button> -->
				<el-button type="primary" :icon="Download" plain @click="ExportXlsx">导出账单报表</el-button>
				<!-- <el-button type="primary" plain @click="toDetail">To 子集详情页面</el-button> -->
				<el-button v-auth="'batchAdd'" type="danger" :icon="Delete" plain :disabled="!scope.isSelected"> 批量删除用户 </el-button>
			</template>
			<!-- Expand -->
			<template #expand="scope">
				{{ scope.row }}
			</template>
			<!-- 表格操作 -->
			<!-- <template #operation="scope">
				<el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
				<el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
				<el-button type="primary" link :icon="Location" @click="openDialog(scope.row.id)">地址</el-button>
			</template> -->
		</ProTable>
		<UserDrawer ref="drawerRef" />
		<ImportExcel ref="dialogRef" />
		<!-- <Address v-model:showDialog="showDialog" :clientId="client_id"></Address> -->
	</div>
</template>

<script setup lang="tsx" name="customers">
import { ref, reactive } from "vue";
import { listReport, listPort } from "@/api/modules/wallet";
import { ColumnProps } from "@/components/ProTable/interface";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import UserDrawer from "@/views/customers/components/UserDrawer.vue";

import { CirclePlus, Delete, EditPen, Download } from "@element-plus/icons-vue";
import XLSX from "xlsx-js-style";
import _ from "lodash";
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	// type: 1
});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
	return {
		list: data.list,
		total: data.count
	};
};
const param: any = ref();
// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
	let newParams = JSON.parse(JSON.stringify(params));
	param.value = params;
	// newParams.username && (newParams.username = "custom-" + newParams.username);
	return listReport(newParams);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const status = reactive([
	{
		userLabel: "启用",
		userStatus: 1
	},
	{
		userLabel: "禁用",
		userStatus: -1
	}
]);
const getPostList = () => {
	return new Promise<void>((resolve, reject) => {
		listPort({
			status: 1,
			limit: 9999
		}).then((res: any) => {
			let data: any = {
				data: res.data.data
			};
			resolve(data);
		});
	});
};

// 表格配置项
const columns: ColumnProps[] = [
	{
		prop: "consign_time",
		label: "发货时间",
		width: 180,
		search: {
			el: "date-picker",
			span: 1,
			props: {
				type: "datetimerange",
				valueFormat: "YYYY-MM-DD HH:mm:ss",
				defaultTime: [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]
			}
		}
	},
	{ prop: "tid", label: "系统单号", minWidth: 150 },
	{
		prop: "waybill_no",
		label: "运单号",
		width: 200,
		search: { el: "input" },
		align: "left",
		render: (scope: { row: any }) => {
			return (
				<>
					<div>主运单号:{scope.row.first_waybill_no}</div>
					<div>从运单号:{scope.row.second_waybill_no}</div>
				</>
			);
		}
	},
	{ prop: "order_no", label: "来源单号", width: 150 },
	{
		prop: "mother_id",
		label: "子母单号",
		width: 200,
		search: { el: "input" },
		align: "left",
		render: (scope: { row: any }) => {
			return (
				<>
					<div>是否子母件:{scope.row.label_data ? (scope.row.label_data.is_mother ? "是" : "否") : ""}</div>
					<div>母单号:{scope.row.mother_info ? scope.row.mother_info.mother_tid : ""}</div>
				</>
			);
		}
	},
	{ prop: "weight", label: "重量", width: 140 },
	{ prop: "goods_type.name", label: "货物类型", width: 140 },
	{
		prop: "port",
		label: "口岸",
		width: 160,
		enum: getPostList,
		search: { el: "select", props: { filterable: true } },
		fieldNames: { label: "port_name", value: "code" },
		render: (scope: { row: any }) => {
			return <>{scope.row.port ? scope.row.port.port_name : ""}</>;
		}
	},
	{
		prop: "trade_code_real",
		label: "真实提单号",
		width: 160,
		render: (scope: { row: any }) => {
			return <>{scope.row.customs_affairs ? scope.row.customs_affairs.code : ""}</>;
		}
	},
	{ prop: "customs_affairs.trade_code", label: "系统提单号", width: 160 },
	{ prop: "customs_affairs.flight.flight_number", label: "航班号", width: 160 },

	{ prop: "sender.name", label: "发件人", width: 140 },
	{ prop: "receiver.user_mark", label: "客户唛头", width: 160 },
	{ prop: "receiver.name", label: "收件人", width: 160 },

	{
		prop: "waybill_no",
		label: "电话",
		width: 200,
		render: (scope: { row: any }) => {
			return (
				<>
					+{scope.row.receiver.area_code} {scope.row.receiver.mobile}
				</>
			);
		}
	},
	{
		prop: "waybill_no",
		label: "地址",
		width: 450,
		render: (scope: { row: any }) => {
			return (
				<>
					{scope.row.receiver.nation}
					{scope.row.receiver.province}
					{scope.row.receiver.city}
					{scope.row.receiver.district}
					{scope.row.receiver.detailed}
				</>
			);
		}
	},
	{ prop: "channel.name", label: "走件渠道", width: 200 },
	{ prop: "remarks", label: "订单备注", width: 250 },
	{ prop: "pay_cost", label: "合计", width: 140 }
];
//
const getPages = () => {
	let querys: any = _.cloneDeep(param.value);
	querys.page = 1;
	return new Promise<any>((resolve, reject) => {
		listReport(querys).then((res: any) => {
			resolve(Math.ceil(res.data.count / querys.limit));
		});
	});
};
const getExcelList = (page: number) => {
	let querys: any = _.cloneDeep(param.value);
	querys.page = page;
	return new Promise<any>((resolve, reject) => {
		listReport(querys).then((res: any) => {
			resolve(res.data.list);
		});
	});
};
//导出表格
const ExportXlsx = async () => {
	let list: any = [];
	let dataList: any = [];
	let pages = await getPages();
	for (let i = 1; i <= pages; ++i) {
		list = list.concat(await getExcelList(i));
	}
	list.forEach((item: any) => {
		let json_fields: any = {
			发货时间: item.consign_time,
			// 系统单号: " " + item.tid,
			主运单号: item.first_waybill_no,
			从运单号: item.second_waybill_no,
			来源单号: item.order_no,
			是否子母件: _.get(item.label_data, "is_mother", "") ? "是" : "否",
			母单号: _.get(item.mother_info, "mother_tid", "") + "",
			重量: item.weight,
			发件人: _.get(item.sender, "name", ""),
			货物类型: _.get(item.goods_type, "name", ""),
			口岸: _.get(item.port, "port_name", ""),
			// 真实提单号: _.get(item.customs_affairs, "code", ""),
			系统提单号: _.get(item.customs_affairs, "trade_code", ""),
			航班号: _.get(item.customs_affairs, "flight.flight_number", ""),
			客户唛头: _.get(item.receiver, "user_mark", ""),
			收件人: _.get(item.receiver, "name", ""),
			电话: "+" + _.get(item.receiver, "area_code", "") + " " + _.get(item.receiver, "mobile", ""),
			地址:
				_.get(item.receiver, "nation", "") +
				_.get(item.receiver, "province", "") +
				_.get(item.receiver, "city", "") +
				_.get(item.receiver, "district", "") +
				_.get(item.receiver, "detailed", ""),
			走件渠道: _.get(item.channel, "name", ""),
			订单备注: item.remarks,
			"合计(₩)": Number(item.pay_cost)
		};
		dataList.push(json_fields);
	});

	// 创建工作表
	const data = XLSX.utils.json_to_sheet(dataList);
	// 创建工作簿
	const wb = XLSX.utils.book_new();
	// 将工作表放入工作簿中
	XLSX.utils.book_append_sheet(wb, data, "data");
	// 生成文件并下载
	XLSX.writeFile(wb, "账单报表.xlsx");
};
</script>
